package tom.spring.cloud.gateway.zuul;

import com.netflix.zuul.FilterFileManager;
import com.netflix.zuul.FilterLoader;
import com.netflix.zuul.groovy.GroovyCompiler;
import com.netflix.zuul.groovy.GroovyFileFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

import javax.annotation.PostConstruct;
import java.io.File;

/**
 * 动态获取路由配置, 启用配置刷新。
 * groovy动态编译，动态增加ZuulFilter
 *
 * @author ZHUFEIFEI
 */
@Slf4j
@RefreshScope
@EnableZuulProxy
@EnableDiscoveryClient
@SpringBootApplication
public class Zuul02Application {
    public static void main(String[] args) {
        SpringApplication.run(Zuul02Application.class, args);
    }

    /**
     * 设置FilterLoader的Compiler，以实现动态编译filter并将filter加入到filterRegistry
     * 注意不是加入到spring容器中，只是加入到zuul的filter列表内
     *
     * @see org.springframework.cloud.netflix.zuul.ZuulServerAutoConfiguration.ZuulFilterConfiguration
     * @see org.springframework.cloud.netflix.zuul.ZuulFilterInitializer
     * @see FilterLoader
     */
    @PostConstruct
    public void dynamicZuulFilter() {
        FilterLoader filterLoader = FilterLoader.getInstance();
        filterLoader.setCompiler(new GroovyCompiler());
        //FilterFileManager实现对指定目录文件的定时扫描
        //GroovyFileFilter只过滤.groovy文件
        FilterFileManager.setFilenameFilter(new GroovyFileFilter());
        try {
            String path = new File(this.getClass().getResource("/").getPath()).getParent()
                    + System.getProperty("file.separator") + "resources/filter";
            //启动一个线程5秒钟扫描一次, 放入filterLoader内的filterRegistry
            FilterFileManager.init(5, path);
            log.info("FilterLoader compiler installed. ");
        } catch (Exception e) {
            log.error("groovy file manger init error!", e);
        }
    }
}
